package com.strongbj.iot.devices.smarrack.request.handle;

import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Preconditions;
import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.iot.devices.smarrack.common.DeviceChannelMap;
import com.strongbj.iot.devices.smarrack.request.entity.LedStateEntity;
import com.strongbj.iot.devices.smarrack.request.message.MQMessage;
import com.strongbj.iot.devices.smarrack.request.message.SmarRackMessageFactory;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
/**
 * 设置LED灯状态
 * @author yuzhantao
 *
 */
public class SetLedStateHandle implements IMessageHandle<MQMessage<Object>,Object> {
	private static Logger logger =  LogManager.getLogger(SetLedStateHandle.class.getName());
	private final static String ACTION_CODE = "SetLed";
	@Override
	public boolean isHandle(MQMessage<Object> t) {
		if(t.getActionCode().equals(ACTION_CODE)){
			return true;
		}else{
			return false;
		}
	}

	@SuppressWarnings("static-access")
	@Override
	public Object handle(ChannelHandlerContext ctx, MQMessage<Object> t) {
		logger.info("从MQ接收到设置LED命令:{}", JSON.toJSONString(t));
		JSONObject jobj = (JSONObject) t.getAwsPostData();
		String deviceCode = (String) jobj.getString("addressCode"); // 获取设备编号
		Preconditions.checkNotNull(deviceCode); // 判断编号是否为空
		
		List<LedStateEntity> ledStates = jobj.getJSONArray("leds").toJavaList(LedStateEntity.class);
		Preconditions.checkArgument(ledStates.size()>0);
		int maxU=0;
		// 获取需要点亮的最大U位
		for(int i=0;i<ledStates.size();i++) {
			int u = ledStates.get(i).getU();
			maxU = Math.max(u, maxU);
		}
		
		byte[] datas = new byte[maxU];
		// 根据硬件协议，开辟1到最大U位的数组，并设置点亮的LED值
		for(int i=0;i<ledStates.size();i++) {
			datas[ledStates.get(i).getU()-1] = ledStates.get(i).getState();
		}
		// 创建下发的电灯命令
		byte[] message = SmarRackMessageFactory.createMessage((byte)0xAB, ByteUtil.hexStringToBytes(deviceCode), datas);
		ByteBuf bs = Unpooled.copiedBuffer(message);
		
		Channel channel = DeviceChannelMap.getInstance().getChannel(deviceCode);
		Preconditions.checkNotNull(channel);
		ChannelFuture cf = channel.writeAndFlush(bs);
		cf.addListener(new ChannelFutureListener() {
			@Override
			public void operationComplete(ChannelFuture future) throws Exception {
				String hexDatas = ByteUtil.byteArrToHexString(message,true);
				if(future.isSuccess()) {
					logger.info("下发设置led命令成功 硬件编号:{}  下发内容:{}",deviceCode,hexDatas);
				}else {
					logger.info("下发设置led命令失败 硬件编号:{}  下发内容:{}",deviceCode,hexDatas);
				}
			}
		
		});
		return null;
	}
}
